package net.trondiz.utorwid;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;




import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class UtorWid extends Activity {
	public Integer a;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		final Button button01 = (Button) findViewById(R.id.Update);		
		// basicly - when button 01 is pressed, do this
		button01.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// infor user something is about to take time
				// should proably be replaced with a loading-dialog
				Toast.makeText(UtorWid.this, "Please wait, downloading text from utorwid.trondiz.net",
						Toast.LENGTH_SHORT).show();

				final TextView textview = (TextView) findViewById(R.id.TorrentOutput);
				String str = DownloadText("http://128.39.42.87:14694/");


				textview.setText(str);
						
					
				
			}
		});
	}


	private void displayBugUglyNetworkErrorMessage() {
		// this code somtimes crash in a emulator, i've been unable to make it
		// crash on a phone
		// http://www.mail-archive.com/android-developers@googlegroups.com/msg68301.html
		AlertDialog.Builder builder = new AlertDialog.Builder(UtorWid.this);
		builder.setCancelable(true);
		builder.setMessage(R.string.no_connection);
		builder.setTitle(R.string.no_connection_title);

		builder.setPositiveButton(R.string.settings_button_text,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						// start/view intent for wlan/3g/etc settings
						startActivity(new Intent(
								Settings.ACTION_WIRELESS_SETTINGS)); 
					}
				});

		builder.setNegativeButton(R.string.cancel_button_text,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Toast.makeText(UtorWid.this, "cancel pressed",
								Toast.LENGTH_SHORT).show();
						return;
					}
				});

		builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				Toast.makeText(UtorWid.this, "Back pressed",
						Toast.LENGTH_SHORT).show();
				return;
			}
		});

		builder.show();
	}

	private String DownloadText(String URL) {
		// replace with
		// http://stackoverflow.com/questions/238547/how-do-you-programmatically-download-a-webpage-in-java
		// ?
		int BUFFER_SIZE = 2000;
		InputStream in = null;
		try {
			in = OpenHttpConnection(URL);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return "Failed to connect";
		}

		InputStreamReader isr = new InputStreamReader(in);
		int charRead;
		String str = "";
		char[] inputBuffer = new char[BUFFER_SIZE];
		try {
			while ((charRead = isr.read(inputBuffer)) > 0) {
				// ---convert the chars to a String---
				String readString = String
						.copyValueOf(inputBuffer, 0, charRead);
				str += readString;
				inputBuffer = new char[BUFFER_SIZE];
			}
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}
		return str;
	}

	private InputStream OpenHttpConnection(String urlString) throws IOException {
		// replace with
		// http://stackoverflow.com/questions/238547/how-do-you-programmatically-download-a-webpage-in-java
		// ?
		InputStream in = null;
		int response = -1;

		URL url = new URL(urlString);
		URLConnection conn = url.openConnection();

		if (!(conn instanceof HttpURLConnection))
			throw new IOException("Not an HTTP connection");

		try {
			HttpURLConnection httpConn = (HttpURLConnection) conn;
			httpConn.setAllowUserInteraction(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn.setRequestMethod("GET");
			httpConn.connect();

			response = httpConn.getResponseCode();
			if (response == HttpURLConnection.HTTP_OK) {
				in = httpConn.getInputStream();
			}
		} catch (Exception ex) {
			throw new IOException("Error connecting");
		}
		return in;
	}

}